#include "album.h"

Album::Album()
{
    img_scr = lv_obj_create(NULL, NULL);
	lv_obj_set_style_local_bg_color(img_scr, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLACK);//设置背景颜色为绿色
	lv_scr_load(img_scr);

    File root = SD.open("/image");
    if (!root||!root.isDirectory())
    {
        lv_style_init(&font_style);
        lv_style_set_text_font(&font_style, LV_STATE_DEFAULT, &lv_font_montserrat_34);
        lv_style_set_text_color(&font_style, LV_STATE_DEFAULT, LV_COLOR_WHITE);
        label = lv_label_create(img_scr, NULL);
        lv_obj_add_style(label, LV_LABEL_PART_MAIN, &font_style);
        lv_label_set_text(label, LV_SYMBOL_EYE_OPEN  " No picture!");
        lv_obj_align(label, NULL, LV_ALIGN_CENTER, 0, 0);
        lv_task_handler();
        return;
    }
    File file = root.openNextFile();
    int num_photo_tmp=0;
    String file_name;
    while (file&&num_photo_tmp<100)
    {
        file_name = file.name();
        if (!file.isDirectory()&&(file_name.endsWith(".jpg")||file_name.endsWith(".jpeg")))
        {
            photo_list[num_photo_tmp] = file_name;
            num_photo_tmp += 1;
        }
        file = root.openNextFile();
    }
    num_photo = num_photo_tmp;
    
    if (num_photo==0)
    {
        lv_style_init(&font_style);
        lv_style_set_text_font(&font_style, LV_STATE_DEFAULT, &lv_font_montserrat_34);
        lv_style_set_text_color(&font_style, LV_STATE_DEFAULT, LV_COLOR_WHITE);
        label = lv_label_create(img_scr, NULL);
        lv_obj_add_style(label, LV_LABEL_PART_MAIN, &font_style);
        lv_label_set_text(label, LV_SYMBOL_EYE_OPEN  " No picture!");
        lv_obj_align(label, NULL, LV_ALIGN_CENTER, 0, 0);
        lv_task_handler();
        return;
    }
    
    timecal = millis()-8000;
    jpg_buf = new uint16_t[19200];
}

void Album::display_ani()
{ 
    
	if ((millis() - timecal > 8000||action==TURN_RIGHT)&&num_photo>0)
	{
        timecal = millis();
        TJpgDec.drawSdJpg(0, 0, photo_list[no_photo].c_str());
        no_photo = (no_photo+1)%num_photo;
        if (action==TURN_RIGHT)
        {
            delay(800);
        }
	}
    else if (action==TURN_LEFT&&num_photo>0)
    {
        timecal = millis();
        TJpgDec.drawSdJpg(0, 0, photo_list[no_photo].c_str());
        no_photo = (no_photo+num_photo-1)%num_photo;
        if (action==TURN_LEFT)
        {
            delay(800);
        }
    }
}

Album::~Album()
{
    lv_obj_del(img_scr);
    delete jpg_buf;
}

Event Album::main_process(Action act)
{
    action = act;
    display_ani();
    return NOEVENT;
}